<?php
class FunnyEffect extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->library ( 'session' );
	}
	public function index() {
		$this->load->Model ( "mimage" );
		
		session_start ();
		$userId = "";
		$imageName = "";
		if (isset ( $_SESSION ["userId"] ))
			$userId = $_SESSION ["userId"];
		else
			redirect ( $this->config->item ["RedirectURL"] );
		if (isset ( $_SESSION ["imageName"] )) {
			$imageName = $_SESSION ["imageName"];
			// only accept jpeg file
			$dotPos = strpos ( $imageName, "." );
			$extension = substr ( $imageName, $dotPos, strlen ( $imageName ) );
			if (strcmp ( $extension, ".png" ) == 0) {
				$this->session->set_flashdata ( "Error", "Please use jpeg or jpg extension photo" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
		} else {
			$_SESSION ["imageName"] = "default.jpg";
			$imageName = $_SESSION ["imageName"];
			// copy default image to userId folder
			$folderName = $userId;
			$destination = './UserUploads/' . $folderName;
			$mode = 0777;
			$mkdirError = ! is_dir ( $destination ) ? mkdir ( $destination, $mode ) : true;
			if (! $mkdirError) {
				$this->session->set_flashdata ( "Error", "There is an error with server" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
			
			$copyFile = copy ( "./UserUploads/default.jpg", $destination . "/default.jpg" );
			if (! $copyFile) {
				$this->session->set_flashdata ( "Error", "There is an error with SERVER" );
				redirect ( base_url ( "index.php/ImageUpload/ImageUpload/index" ) );
				return;
			}
		}
		if(isset($_SESSION["imagePath"]))
			$size = $this->mimage->getSize($_SESSION["imagePath"]);
		else 
			$size = $this->mimage->getSize("./UserUploads/$userId/default.jpg");
		$data ["userId"] = $_SESSION ["userId"];
		$data ['imageName'] = (! isset ( $_SESSION ["isFunnyEffect"] )) ? ((isset($_SESSION["imagePath"]))?$_SESSION ["imagePath"]:(base_url()."./UserUploads/$userId/default.jpg")) : $_SESSION ["funnyEffectPath"];
		$data ["width"] = $size [0];
		$data ["height"] = $size [1];
		$data ["funcType"] = 5;
		// copy original image into wartermark one
		
		$this->load->view ( 'FunctionFunnyEffect/index', $data );
	}
	public function process() {
		if (isset ( $_POST )) {
			var_dump ( $_POST );
			$beardNumber = $_POST ["beard-style"];
			$hairNumber = $_POST ["hair-style"];
			$noseNumber = $_POST ["nose-style"];
			$this->load->Model ( 'mimage' );
			
			$beardPath = ! ($beardNumber == 0) ? "images/FunnyEffect/Beard/$beardNumber.png" : "";
			$hairPath = ! ($hairNumber == 0) ? "images/FunnyEffect/Hair/$hairNumber.png" : "";
			$nosePath = ! ($noseNumber == 0) ? "images/FunnyEffect/Nose/$noseNumber.png" : "";
			$this->mimage->makeFunnyEffect ( $beardPath, $hairPath, $nosePath, $_POST );
			redirect ( base_url ( "index.php/FunctionFunnyEffect/FunnyEffect/index" ) );
		}
	}
}